package com.ziguang.redwood.websocket.chat;

import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import java.util.logging.Logger;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

@ServerEndpoint(value = "/websocket/chatr")
public class ChatEndpoint {  
	
	 private static final Logger log = Logger.getLogger(ChatEndpoint.class.getName());
	 
	private Session session;
	private String sender;
	private List<String> roomIds;
	
	
	@OnOpen
	public void start(Session session)
	{
		this.session = session;
	}
	

    @OnMessage
    public void incoming(String str) 
    {
    	Request msg = Coder.decode(str);
    	
    	//加入消息
    	if(msg.getType() == Request.JOIN_QUEST)
    	{
    		sender = msg.getSender();
    		roomIds = new ArrayList<String>();
    		StringTokenizer st = new StringTokenizer(msg.getRooms(),",");
    		while(st.hasMoreTokens())
    		{
    			roomIds.add(st.nextToken());
    		}
    		ChatRoom.getInstance().join(this);
    		
    	}
    	else if(msg.getType() == Request.CHAT_QUEST)//发送消息
    	{
    		String targetRoom = msg.getRooms();
    		String sender = msg.getSender();
    		String content = msg.getBody();
    		String niceName = msg.getNiceName();
    		ChatRoom.getInstance().msgBrocast(sender, targetRoom, content, niceName);
    	}
    	else if(msg.getType() == Request.ONlINE_USER_QUEST)//上线用户
    	{
    		String targetRoom = msg.getRooms();
    		ChatRoom.getInstance().getOnlineUsers(this,targetRoom);
    	}
    	
    }
    
    
    @OnClose
    public void end() {
    	ChatRoom.getInstance().quit(this);
    }


    @OnError
    public void onError(Throwable t) throws Throwable {
        log.warning(t.getMessage());
        System.out.println(t.getCause());
    }

	public Session getSession() {
		return session;
	}


	public String getSender() {
		return sender;
	}


	public List<String> getRoomIds() {
		return roomIds;
	}
	
}
